package com.ocom.srvpaccess.controller;

import com.ocom.common.constant.SrvpAccessDeviceUrl;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.entity.access.EntityMjTimeInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.common.vo.srvpaccess.PerGroupDataVo;
import com.ocom.srvpaccess.service.MjDeviceInfoService;
import com.ocom.srvpaccess.service.TimeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class GroupParaController {
    @Autowired
    private MjDeviceInfoService mjDeviceInfoService;


    @Autowired
    private TimeInfoService timeInfoService;

    // 获取权限组参数（getGroupPara）
    @GetMapping(value = SrvpAccessDeviceUrl.URLP_ACCESSDEVICE_getGroupPara)
    public RespMachMessage getGroupPara(Long companyId, String machNo, Long perGroupNum) {
        //判断参数
        if (companyId <= 0 || machNo == null) {
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }


        //从设备信息表mj_device_info找到com_id ，device_no匹配的记录
        EntityMjDeviceInfo mjDeviceInfo = mjDeviceInfoService.getDeviceInfo(companyId, machNo);
        //如果没有记录：返回NULL
        if (mjDeviceInfo == null) {
            RespUtilMach.success(null);
        }
        //否则：areaNo = mj_device_info . area_id
        Long areaId = mjDeviceInfo.getAreaId();
        //2、如果perGroupNum=0：mj_device_info . group_var_last = mj_device_info . group_ver
        if (perGroupNum == 0) {
            mjDeviceInfoService.updateGroupVarLast(mjDeviceInfo.getComId(), mjDeviceInfo.getDeviceNo(), mjDeviceInfo.getGroupVer());
        }
        if (mjDeviceInfo.getGroupVerLast() == null || !mjDeviceInfo.getGroupVerLast().equals(mjDeviceInfo.getGroupVer())) {
            return RespUtilMach.success(null);
        }
        //3、从门禁时段表mj_time_info查找记录：
        List<EntityMjTimeInfo> entityMjTimeInfos = timeInfoService.selectGroupNo(companyId, perGroupNum, areaId);
        //如果没有记录：mj_device_info . group_var_tab = mj_device_info . group_ver_last，返回NULL
        if (entityMjTimeInfos.size() == 0) {
            try {
                mjDeviceInfoService.updateGroupVarTab(mjDeviceInfo.getComId(), mjDeviceInfo.getDeviceNo(), mjDeviceInfo.getGroupVerLast());
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return RespUtilMach.success(null);
        }

        EntityMjTimeInfo entityMjTimeInfo = entityMjTimeInfos.get(0);

        List<EntityMjTimeInfo> mjTimeInfos = timeInfoService.selectTimeInfo(companyId,entityMjTimeInfo.getGroupNo());

        //否则：pergroupnum=0，timezone =0，perGroupData=NULL

        Long pergroupnum = 0L;
        Map<String, Object> data = new HashMap<>();


        Map<Long, PerGroupDataVo> longMapMap = new HashMap<>();

        boolean existPer=false; //判断是否拿到权限组
        //循环读取记录,只取一条pergroupnum
        for (EntityMjTimeInfo timeInfo : entityMjTimeInfos) {
            if(!existPer){
                pergroupnum = timeInfo.getGroupNo();
                existPer=true;
            }
            if(pergroupnum != timeInfo.getGroupNo()){
                continue;
            }
            if(!longMapMap.containsKey(timeInfo.getZoneNo())){
                PerGroupDataVo perGroupDataVo =new PerGroupDataVo();
                perGroupDataVo.setTimezone(timeInfo.getZoneNo());
                perGroupDataVo.getStartEndTime().add(timeInfo.getBeginTime() + "-" + timeInfo.getEndTime() + "-"+ timeInfo.getDirection());
                longMapMap.put(timeInfo.getZoneNo(),perGroupDataVo);
            }else{
                PerGroupDataVo perGroupDataVo =longMapMap.get(timeInfo.getZoneNo());
                perGroupDataVo.getStartEndTime().add(timeInfo.getBeginTime() + "-" + timeInfo.getEndTime() + "-"+ timeInfo.getDirection());
                longMapMap.put(timeInfo.getZoneNo(),perGroupDataVo);
            }
        }

        List<PerGroupDataVo> listFun = new ArrayList<>();
        for (Map.Entry<Long, PerGroupDataVo> map3 : longMapMap.entrySet()) {
            listFun.add(map3.getValue());
        }

        data.put("pergroupnum", pergroupnum);
        data.put("list", listFun);

        return RespUtilMach.success(data);

    }

    // 获取权限组参数（getGroupPara） 原返回实例不符合文档要求，新增方法
    @GetMapping(value = SrvpAccessDeviceUrl.URLP_ACCESSDEVICE_getGroupParaNew)
    public RespMachMessage getGroupParaNew(Long companyId, String machNo, Long perGroupNum) {
        //判断参数
        if (companyId <= 0 || machNo == null) {
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        //从设备信息表mj_device_info找到com_id ，device_no匹配的记录
        EntityMjDeviceInfo mjDeviceInfo = mjDeviceInfoService.getDeviceInfo(companyId, machNo);
        //如果没有记录：返回NULL
        if (mjDeviceInfo == null) {
            RespUtilMach.success(null);
        }
        //否则：areaNo = mj_device_info . area_id
        Long areaId = mjDeviceInfo.getAreaId();
        //2、如果perGroupNum=0：mj_device_info . group_var_last = mj_device_info . group_ver
        if (perGroupNum == 0) {
            mjDeviceInfoService.updateGroupVarLast(mjDeviceInfo.getComId(), mjDeviceInfo.getDeviceNo(), mjDeviceInfo.getGroupVer());
        }
        if (mjDeviceInfo.getGroupVerLast() == null || !mjDeviceInfo.getGroupVerLast().equals(mjDeviceInfo.getGroupVer())) {
            return RespUtilMach.success(null);
        }
        //3、从门禁时段表mj_time_info查找记录：
        List<EntityMjTimeInfo> entityMjTimeInfos = timeInfoService.selectGroupNo(companyId, perGroupNum, areaId);
        //如果没有记录：mj_device_info . group_var_tab = mj_device_info . group_ver_last，返回NULL
        if (entityMjTimeInfos.size() == 0) {
            try {
                mjDeviceInfoService.updateGroupVarTab(mjDeviceInfo.getComId(), mjDeviceInfo.getDeviceNo(), mjDeviceInfo.getGroupVerLast());
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return RespUtilMach.success(null);
        }
        //否则：pergroupnum=0，timezone =0，perGroupData=NULL
        List<Object> perGroupData = new ArrayList<>();
        Long pergroupnum = 0L;
        Long timezone = 0L;
        List<String> startEndtime = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        Map<String, Object> data = new HashMap<>();


        Map<Long, PerGroupDataVo> longMapMap = new HashMap<>();

        boolean existPer=false; //判断是否拿到权限组
        //循环读取记录,只取一条pergroupnum
        for (EntityMjTimeInfo timeInfo : entityMjTimeInfos) {
            if(!existPer){
                pergroupnum = timeInfo.getGroupNo();
                existPer=true;
            }
            if(pergroupnum != timeInfo.getGroupNo()){
                continue;
            }
            if(!longMapMap.containsKey(timeInfo.getZoneNo())){
                PerGroupDataVo perGroupDataVo =new PerGroupDataVo();
                perGroupDataVo.setTimezone(timeInfo.getZoneNo());
                perGroupDataVo.getStartEndTime().add(timeInfo.getBeginTime() + "-" + timeInfo.getEndTime() + "-"+ timeInfo.getDirection());
                longMapMap.put(timeInfo.getZoneNo(),perGroupDataVo);
            }else{
                PerGroupDataVo perGroupDataVo =longMapMap.get(timeInfo.getZoneNo());
                perGroupDataVo.getStartEndTime().add(timeInfo.getBeginTime() + "-" + timeInfo.getEndTime() + "-"+ timeInfo.getDirection());
                longMapMap.put(timeInfo.getZoneNo(),perGroupDataVo);
            }
        }
//            //a)第一次pergroupnum==0
//            if (pergroupnum == 0) {
//                //pergroupnum= mj_time_info. group_no
//                pergroupnum = entityMjTimeInfo.getGroupNo();
//            }
//            //第二个pergroupnum，跳出循环，返回perGroupData
//            else if (pergroupnum != entityMjTimeInfo.getGroupNo()) {
//                break;
//            }
//            //第一次timezone=0
//            if(timezone==0){
//                timezone = entityMjTimeInfo.getZoneNo();
//            }
//            //第二个pergroupnum，添加timezone， 重置startEndtime
//            else if (timezone != entityMjTimeInfo.getZoneNo()) {
//                map.put("timeZone", timezone);
//                map.put("startEndtime", startEndtime);
//                perGroupData.add(map);
//                Isload=false;
//                //	增加时区timezone = mj_time_info. zone _no，start_endtime=[ ]
//                timezone = entityMjTimeInfo.getZoneNo();
//                startEndtime = new ArrayList<>();
//
//            }
//            //添加开始-结束时间
//            startEndtime.add(entityMjTimeInfo.getBeginTime() + "-" + entityMjTimeInfo.getEndTime()+ "-" +entityMjTimeInfo.getDirection()) ;
//            Isload=true;


        List<PerGroupDataVo> listFun = new ArrayList<>();
        for (Map.Entry<Long, PerGroupDataVo> map3 : longMapMap.entrySet()) {
            listFun.add(map3.getValue());
        }

        data.put("perGroupNum", pergroupnum);
        data.put("perGroupData", listFun);

        return RespUtilMach.success(data);
    }


}